package com.itcast.msm.controller;

import com.itcast.common.result.R;
import com.itcast.common.utils.RandomUtil;
import com.itcast.msm.service.MsmApiService;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 发送短信服务
 */


@RestController
@RequestMapping("/api/msm")
public class MsmApiController {
    //引入serivce依赖
    @Resource
    private MsmApiService msmApiService;

    //引入redis的依赖
    @Resource
    private RedisTemplate<String,String> redisTemplate;

    //发送短信的方法
    @GetMapping("/send/{phone}")
    public R send(@PathVariable String phone){
        //1.根据手机号查询reids如果查询到验证码就直接返回
        String code = redisTemplate.opsForValue().get(phone);
        System.out.println(code);
        if(!StringUtils.isEmpty(code)){
            return R.ok();
        }
        //2.如果没有查询通过random来生成随机的验证码
        code = RandomUtil.getFourBitRandom();
        System.out.println("验证码为:"+code);
        //3.进行短信的发送 返回一个状态 发送成功返回true  发送失败返回false
        Map<String,Object> map = new HashMap<>();
        map.put("code",code);
        boolean isSend = msmApiService.send(phone,"SMS_180051135",map);
        //4.判断发送的状态如果为true
        if(isSend){
            //把发送的验证码存储到redis中
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        }else{
            //5.如果为false就返回发送短信失败
            return R.error().message("短信发送失败!");
        }
    }
}
